<template>
  <div>
    <div class="ky-mb10 flex flex-row justify-between align-center">
      <el-button size="small" @click="addColumnsConfig" type="primary">新增</el-button>
      <div class="red">拖动列表可进行排序</div>
      <div style="float:right">
        <el-button size="small" @click="resetSave" type="success" v-if="from != 'applyHis' && isHasCustomSet">取消个人自定义列表配置并保存</el-button>
        <el-button size="small" @click="resetConfig(1)" v-if="from == 'applyHis'" type="primary">重置为初始数据</el-button>
        <el-button size="small" @click="resetConfig" v-else type="primary">重置为医院默认数据</el-button>
      </div>
    </div>
    <el-table :data="tableDataColumnsConfig" class="ky-table his-table-data" height="570">
      <el-table-column label="序号" width="55" align="center">
        <template slot-scope="{ $index }">
          {{tableDataColumnsConfig[$index].key}}
        </template>
      </el-table-column>
      <el-table-column label="名称">
        <template slot-scope="{ $index }">
          <el-input size="small" v-model="tableDataColumnsConfig[$index].label"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="字段">
        <template slot-scope="{ $index }">
          <el-select size="mini" clearable filterable allow-create placeholder="字段" style="width: 100%;" @change="tableDataChange($index)" v-model="tableDataColumnsConfig[$index].prop">
            <el-option v-for="(item, index) in tableDataColumnLabel" :key="index" :label="item.prop" :value="item.prop">
              <span style="float: left">{{item.prop}}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{item.label}}</span>
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="宽度" width="150">
        <template slot-scope="{ $index }">
          <el-input size="small" v-model="tableDataColumnsConfig[$index].width"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="显示" width="150">
        <template slot-scope="{ $index }">
          <el-switch
            size="small"
            v-model="tableDataColumnsConfig[$index].show"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="是"
            inactive-text="否">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="" width="50">
        <template slot-scope="{ $index }">
          <el-button type="text" size="small" @click="delColumnusConfig($index)">
            <i class="el-icon-delete fc_red"></i>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import { Options } from '@/utils/constant'
import Sortable from 'sortablejs'
import { postSetuserparamtersettings } from '@/api/api'
export default {
  props: {
    from: { // 如果值是applyHis 就代表只要医院配置的参数
      type: String,
      default: ''
    },
    dialogVisibleParent: {
      type: Boolean,
      default: false
    }
    // tableDataColumnsConfig: {
    //   type: Array,
    //   default: JSON.parse(JSON.stringify(Options.checkTableColumnsConfig))
    // }
  },
  data() {
    return {
      isHasCustomSet: false,
      tableDataColumnsConfig: JSON.parse(JSON.stringify(Options.checkTableColumnsConfig)),
      tableDataColumnLabel: JSON.parse(JSON.stringify(Options.checkTableColumnsConfig)).sort((a, b) => a.prop.localeCompare(b.prop)),
      configInfo: {
        baseConfig: {},
        checkHisTable: [],
        checkPatTypeTable: [],
        checkHisTableColumnsConfig: []
      },
      tbodyList: null
    }
  },
  computed: {
    paramConfig() {
      return this.$store.state.settings.paramConfig
    }
  },
  watch: {
    dialogVisibleParent: {
      handler(val) {
        if (val) {
          this.isHasCustomSet = false
          this.setTableCol()
          this.tableDataColumnsConfig.forEach((item, index) => {
            item.key = index + 1
            item.id = index + 1
          })
          this.$nextTick(() => {
            this.tbodyList = document.querySelector('.his-table-data .el-table__body-wrapper tbody')
            Sortable.create(this.tbodyList, {
              ghostClass: 'sortable-drag',
              chosenClass: 'sortable-drag',
              dragClass: 'sortable-drag',
              onEnd: (event) => {
                const { oldIndex, newIndex } = event
                this.updateRowOrder(oldIndex, newIndex)
              }
            })
          })
        }
      },
      immediate: true
    }
  },
  mounted() {
  },
  methods: {
    addColumnsConfig() {
      const _columns = JSON.parse(JSON.stringify(this.tableDataColumnsConfig))
      _columns.unshift({ label: '', width: '100', prop: '', show: true, sort: 0 })
      this.tableDataColumnsConfig = _columns
    },
    delColumnusConfig(idx) {
      this.tableDataColumnsConfig.splice(idx, 1)
      this.tableDataColumnsConfig.forEach((item, index) => {
        item.sort = index + 1
        item.key = index + 1
        item.id = index + 1
      })
    },
    // 列表数据配置
    setColumnsTable(columnsConfig) {
      let _d = []
      columnsConfig.forEach((item, index) => {
        // { label: '患者', width: '90', prop: 'patientName', show: true, sort: 1 },
        let obj = {
          label: item.name || item.label,
          width: item.width,
          prop: item.prop,
          show: item.show,
          sort: index + 1
        }
        _d.push(obj)
      })
      this.tableDataColumnsConfig = _d
    },
    // 重置保存个人用户信息
    resetSave() {
      let userParamsConfig = JSON.parse(this.paramConfig.userParameterContent)
      delete userParamsConfig.hisTable
      // userParamsConfig.hisTable = []
      const params = {
        hospitalCode: this.$store.state.user.hospitalCode,
        userId: this.$store.state.user.id,
        parameterContent: JSON.stringify(userParamsConfig)
      }
      postSetuserparamtersettings(params).then(res => {
        if (res && res.code === 10000) {
          this.$message.success(res.message || '设置用户配置参数成功！')
          this.dialogVisible = false
          // if (this.hospitalCode === this.$store.state.user.hospitalCode) {
          //   this.$store.dispatch('settings/getAppConfigSetting')
          // }
          window.location.reload()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    updateRowOrder(oldIndex, newIndex) {
      const movedItem = this.tableDataColumnsConfig.splice(oldIndex, 1)[0]
      this.tableDataColumnsConfig.splice(newIndex, 0, movedItem)
      const _columns = JSON.parse(JSON.stringify(this.tableDataColumnsConfig))
      _columns.forEach((item, index) => {
        item.key = index + 1
        item.id = index + 1
        item.sort = index + 1
      })
      let scrollTop = 0
      let $tbody = document.querySelector('.his-table-data .el-table__body-wrapper')
      scrollTop = $tbody.scrollTop
      this.tableDataColumnsConfig = []
      this.$nextTick(() => {
        this.tableDataColumnsConfig = _columns
        this.$nextTick(() => {
          $tbody.scrollTop = scrollTop
        })
      })
    },
    setTableCol() {
      this.configInfo = {}
      // 有医院配置先取医院
      if (this.paramConfig.hospitalParameterContent) {
        this.configInfo = this.paramConfig.hospitalParameterContent
        this.configInfo1 = JSON.parse(this.configInfo)
        if (this.configInfo1.checkHisTableColumnsConfig) {
          this.hospitalTableColumnConfig = this.configInfo1.checkHisTableColumnsConfig
          this.tableDataColumnsConfig = this.configInfo1.checkHisTableColumnsConfig
        }
      }
      // // 有个人配置 个人比较高级 通常会只有一个{}的时候出现
      if (this.from !== 'applyHis' && this.paramConfig.userParameterContent) {
        this.configInfo = this.paramConfig.userParameterContent
        this.configInfo1 = JSON.parse(this.configInfo)
        if (this.configInfo1.hisTable) {
          this.isHasCustomSet = true
          this.tableDataColumnsConfig = this.configInfo1.hisTable
        }
      }

      // // 都没有拿默认的
      if (!this.tableDataColumnsConfig || Array.isArray(this.tableDataColumnsConfig) && this.tableDataColumnsConfig.length == 0) {
        this.tableDataColumnsConfig = JSON.parse(JSON.stringify(Options.checkTableColumnsConfig))
        this.hospitalTableColumnConfig = JSON.parse(JSON.stringify(Options.checkTableColumnsConfig))
      }
    },
    resetConfig(init) {
      if (init == 1) {
        this.tableDataColumnsConfig = JSON.parse(JSON.stringify(Options.checkTableColumnsConfig))
      } else {
        this.tableDataColumnsConfig = this.hospitalTableColumnConfig ? JSON.parse(JSON.stringify(this.hospitalTableColumnConfig)) : JSON.parse(JSON.stringify(Options.checkTableColumnsConfig))
      }
      this.tableDataColumnsConfig.forEach((item, index) => {
        item.key = index + 1
      })
    },
    tableDataChange(index) {
      const selectedLabel = this.tableDataColumnsConfig[index].prop
      this.tableDataColumnLabel.forEach((item, i) => {
        if (item.prop === selectedLabel) {
          this.tableDataColumnsConfig[index].label = item.label
          this.tableDataColumnsConfig[index].show = item.show
          this.tableDataColumnsConfig[index].sort = item.sort
          this.tableDataColumnsConfig[index].width = item.width
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
    .config_container{
      display: inline-block;
      .setting_btn{
        padding: 2px;
        color: #666;
        font-size: 20px;
        cursor: pointer;
        &:hover{
          color: #00C0EF
        }
      }
    }
    .config_setting_dialog{
      /deep/ .el-dialog__body{
        padding: 5px 20px;
        max-height: calc(100vh - 220px);
        overflow-y: auto;
      }
    }
    /deep/ .sortable-drag {
      background: #C7F2F9;
    }
    /deep/ .mrg-btn.el-button--small{
      padding: 0px !important;
    }
  </style>
